/*
 * @Author: jiu yin
 * @Date: 2023-06-06 09:37:12
 * @LastEditTime: 2023-06-06 14:47:30
 * @LastEditors: jiu yin zhen jing
 * @FilePath: \AI admin\src\view\tag\index.tsx
 * jiu
 */

import { useState, useEffect, useRef, useCallback, useMemo } from 'react'
import './index.scss'
import { Space, Table, Tag, Tooltip, Modal, Button, Input, Switch, Form, theme, Checkbox } from 'antd';
import type { ColumnsType } from 'antd/es/table';

import { useNavigate } from 'react-router-dom'
import { getRandomHexColor,getColorArr } from "@/utils"

import { PlusOutlined } from '@ant-design/icons';
import type { InputRef } from 'antd';
import { TweenOneGroup } from 'rc-tween-one';



function Intention() {
    const [form] = Form.useForm();
    let navigate = useNavigate()
    let getColorArrLen = getColorArr().length
    interface DataType {
        key: string;
        name: string;
        age: number;
        address: string;
        status: boolean
    }
    const SwitchOnchange = (checked: boolean, item: any) => {
        console.log(`Switch checked: ${checked}`, item);
        let arr = datas.map(i => {
            if (i.key === item.key) {
                return { ...i, status: checked }
            }
            return i
        })
        setDatas(arr)
    }

    const columns: ColumnsType<DataType> = [
        {
            title: '标签ID',
            dataIndex: 'name',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '标签名',
            dataIndex: 'age',
        },
        {
            title: '类型',
            dataIndex: 'age',
        },
        {
            title: '标签',
            dataIndex: 'address',

        },
        {
            title: '近义词库',
            dataIndex: 'address',
            render: (_, item) => (
                <>
                    <Tooltip title={item.address}>
                        <p className='tableP'>{item.address}</p>
                    </Tooltip>
                </>
            ),

        },
        {
            title: '状态',
            key: 'status',
            render: (_, item) => (
                <>
                    <Switch defaultChecked checked={item.status} onChange={(checked) => { SwitchOnchange(checked, item) }} />
                </>
            ),
        },
        {
            title: '操作',
            key: 'action',
            render: (_, item) => (
                <Space size="middle">
                    <a href='#' onClick={() => detail(item)}>详情</a>
                    <a href='#' onClick={() => edit(item)}>编辑</a>
                    <a href='#'>删除</a>
                </Space>
            ),
        },
    ];


    let [isDetail, setIsDetail] = useState(false)
    //详情
    const detail = (id) => {
        setIsModalOpen(true)
        //禁用打开
        setIsDetail(true)

    }

    // 编辑
    const edit = (id) => {
        setIsModalOpen(true)
    }

    const data: DataType[] = [
        {
            key: '1',
            name: 'John Brown',
            age: 32,
            address: 'New York No. 1 Lake Park',
            status: false,
        },
        {
            key: '2',
            name: 'Jim Green',
            age: 42,
            address: 'London No. 1 Lake Park',
            status: true,
        },
        {
            key: '3',
            name: 'Joe Black',
            age: 32,
            address: 'Sydney No. 1 Lake Park',
            status: false,
        },

    ];

    const [datas, setDatas] = useState(data)

    //搜索框
    let searchInit = { dim: "" }
    const [search, setSearch] = useState(searchInit)

    const onSearch = () => {
        console.log(search);
    }

    //弹框
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [formData, setFormData] = useState({ synonym: "block" } as any)

    //取消
    const cancel = () => {
        setIsModalOpen(false)
        setIsDetail(false)
        setInputVisible(false)
        setTags([])
        setFormData({ synonym: "block" })
        form.resetFields();
    }



    const { token } = theme.useToken();
    const [tags, setTags] = useState([] as string[]);
    const [inputVisible, setInputVisible] = useState(false);
    const [inputValue, setInputValue] = useState('');
    const inputRef = useRef<InputRef>(null);

    //成功走得
    const onFinish = (values: any) => {
        console.log('Success:', values, tags);
        // setIsModalOpen(false);
    };

    //失败走得
    const onFinishFailed = (errorInfo: any) => {
        console.log('Failed:', errorInfo);
        // setIsModalOpen(false);
    };





    //标签功能

    useEffect(() => {
        if (inputVisible) {
            inputRef.current?.focus();
        }
    }, [inputVisible]);

    const handleClose = (removedTag: string) => {
        const newTags = tags.filter((tag) => tag !== removedTag);
        console.log(newTags);
        setTags(newTags);
    };

    const showInput = () => {
        setInputVisible(true);
    };

    const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
        setInputValue(e.target.value);
    }, [inputValue])

    const handleInputConfirm = (e: any) => {
        e.stopPropagation();
        e.preventDefault()
        if (inputValue && tags.indexOf(inputValue) === -1) {
            setTags([...tags, inputValue]);
        }
        setInputVisible(true);
        setInputValue('');
    };



    const forMap = (tag: string, index: number) => {
        const tagElem = (
            <Tag
                closable
                key={index}
                onClose={(e) => {
                    e.preventDefault();
                    handleClose(tag);
                }}
                color={getColorArr()[index % getColorArrLen]} 
                className='tagSynonym'
            >
                {tag}
            </Tag>
        );
        return (
            <span key={tag} style={{ display: 'inline-block' }}>
                {tagElem}
            </span>
        );
    };

    const tagChild = useMemo(() => tags.map(forMap), [tags]);

    const tagPlusStyle = {
        background: token.colorBgContainer,
        borderStyle: 'dashed',
        marginLeft: '5px',
    };




    const optionsChenckbox = [
        { label: '场景', value: 'Apple' },
        { label: '媒体', value: 'Pear' },
    ];


    return (
        <div className='intention'>
            <div className='title'>
                <Button type="primary" onClick={() => { setIsModalOpen(true); setIsDetail(false) }}>+ 添加标签</Button>
                <div className='search'>
                    <Input placeholder="模糊搜索关键字" className='input' value={search.dim} onChange={(e) => setSearch({ ...search, dim: e.target.value })} />
                    <Button type="primary" className='ml_10' onClick={onSearch}>查询</Button>
                    <Button className='ml_10' onClick={() => setSearch(searchInit)}>重置</Button>
                </div>
            </div>
            <Table columns={columns} dataSource={datas} />

            {isModalOpen && <Modal title="添加标签" open={isModalOpen} onCancel={() => { cancel() }} keyboard footer={null}>

                <Form
                    name="basic"
                    labelCol={{ span: 6, offset: 2 }}
                    wrapperCol={{ span: 100 }}
                    style={{ maxWidth: 600, marginTop: "20px" }}
                    initialValues={formData}
                    onFinish={onFinish}
                    onFinishFailed={onFinishFailed}
                    autoComplete="off"
                    form={form}
                    disabled={isDetail}
                >
                    <Form.Item
                        label="标签名"
                        name="username"
                        rules={[{ required: true, message: '请输入标签名！' }]}
                    >
                        <Input />
                    </Form.Item>

                    <Form.Item
                        label="近义词表"
                        name="synonym"
                        className='ant-form-item-required'
                        rules={[
                            { required: true, message: '请输入标签名！' },
                            {
                                validator: (_, value) =>
                                    tags.length > 0 ? Promise.resolve() : Promise.reject(new Error('请输入近义词表')),
                            },
                        ]}
                    >
                        <div className='synonym'>

                            {/* ui复制的标签表 */}
                            <div style={{ marginBottom: 16 }}>
                                <TweenOneGroup
                                    enter={{
                                        scale: 0.8,
                                        opacity: 0,
                                        type: 'from',
                                        duration: 100,
                                    }}
                                    onEnd={(e: any) => {
                                        if (e.type === 'appear' || e.type === 'enter') {
                                            (e.target as any).style = 'display: inline-block';
                                        }
                                    }}
                                    leave={{ opacity: 0, width: 0, scale: 0, duration: 200 }}
                                    appear={false}
                                >
                                    {tagChild}
                                </TweenOneGroup>
                            </div>
                            {inputVisible ? (
                                <Input
                                    ref={inputRef}
                                    type="text"
                                    size="small"
                                    style={{ width: 78 }}
                                    value={inputValue}
                                    onChange={handleInputChange}
                                    onBlur={(e) => handleInputConfirm(e)}
                                    onPressEnter={(e) => handleInputConfirm(e)}
                                />
                            ) : (
                                <Tag onClick={showInput} style={tagPlusStyle}>
                                    <PlusOutlined /> 添加新标签
                                </Tag>
                            )}

                        </div>
                        <p className='mr_t0'>注：输入词汇后按回车键完成</p>
                    </Form.Item>




                    <Form.Item
                        label="标签类型"
                        name="asdadad"
                    >
                        <Checkbox.Group options={optionsChenckbox} />
                    </Form.Item>

                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button type="primary" htmlType="submit">
                            确定
                        </Button>
                        <Button htmlType="button" onClick={() => { cancel() }} className='ml_10'>
                            取消
                        </Button>
                    </Form.Item>
                </Form>


            </Modal>}
        </div>
    )
}

export default Intention
